package com.observatory.baapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

public class NotificationDialogActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String title = getIntent().getStringExtra("title");
        String message = getIntent().getStringExtra("message");
        String triggerName = parseTriggerName(message); // 从消息中提取关键参数

        // 加载自定义布局
        View dialogView = LayoutInflater.from(this).inflate(R.layout.custom_notification_dialog, null);

        // 初始化视图组件
        TextView tvTitle = dialogView.findViewById(R.id.dialog_title);
        TextView tvMessage = dialogView.findViewById(R.id.dialog_message);
        Button btnClose = dialogView.findViewById(R.id.btn_close);
        Button btnConfirm = dialogView.findViewById(R.id.btn_confirm);

        // 设置对话框内容
        tvTitle.setText(title != null ? title : "新天文事件预警");
        tvMessage.setText(message != null ? message : "");

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(dialogView)
                .setCancelable(false)
                .create();

        // 设置对话框窗口样式
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }

        // 关闭按钮点击事件
        btnClose.setOnClickListener(v -> {
            dialog.dismiss();
            finish();
        });

        // 确定按钮点击事件
        btnConfirm.setOnClickListener(v -> {
            navigateToEventDetails(triggerName);
            dialog.dismiss();
            finish();
        });

        dialog.setOnDismissListener(dialogInterface -> finish());
        dialog.show();
    }
    private static final String TAG = "NotificationDialogActivity";
    private String parseTriggerName(String message) {
        String triggerName = "";
        // 修改解析逻辑，去除 triggerName: 前缀的判断
        String[] parts = message.split(",");
        if (parts.length > 1) {
            triggerName = parts[1].trim();
        }
        return triggerName;
    }

    private void navigateToEventDetails(String triggerName) {
        Log.d(TAG, "Parsed triggerName: " + triggerName);
        Intent intent = new Intent(NotificationDialogActivity.this, MainActivity.class);
        intent.putExtra("NAVIGATE_TO", "EventDetails");
        intent.putExtra("triggerName", triggerName);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        finish();
    }
}
